﻿using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;

namespace MongoScienceDAL.Core
{
    public class ScienceEntryBsonWriter
    {
        private readonly BsonWriter _bsonWriter;

        public ScienceEntryBsonWriter(BsonWriter bsonWriter)
        {
            _bsonWriter = bsonWriter;
        }

        public void Write(ScienceTypeEnum type, string key, object value)
        {
            switch (type)
            {
                case ScienceTypeEnum.Text:
                    _bsonWriter.WriteString(key, (string)value);
                    break;
                case ScienceTypeEnum.DateTime:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteDateTime(key, BsonDateTime.Create((DateTime)value).MillisecondsSinceEpoch);
                    break;
                case ScienceTypeEnum.Value:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteDouble(key, (double)value);
                    break;
                case ScienceTypeEnum.ValueSet:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteName(key);
                    BsonSerializer.Serialize(_bsonWriter, typeof(List<double>), value);
                    break;
                case ScienceTypeEnum.Files:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteName(key);
                    BsonSerializer.Serialize(_bsonWriter, typeof(List<ScienceFile>), value);
                    break;
                case ScienceTypeEnum.VersionedFile:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteName(key);
                    BsonSerializer.Serialize(_bsonWriter, typeof(List<ScienceFile>), value);
                    break;
                case ScienceTypeEnum.ParentLink:
                    if (string.IsNullOrEmpty(value.ToString())) break;
                    _bsonWriter.WriteName(key);
                    BsonSerializer.Serialize(_bsonWriter, typeof(ObjectId), value);
                    break;
                case ScienceTypeEnum.ChildLinks:
                    _bsonWriter.WriteName(key);
                    BsonSerializer.Serialize(_bsonWriter, typeof(List<ObjectId>), value);
                    break;
                case ScienceTypeEnum.Boolean:
                    _bsonWriter.WriteBoolean(key, (bool)value);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}
